#include "mypushbutton.h"
#include <QDebug>
#include <QPropertyAnimation>

MyPushButton::MyPushButton(QString normalImg, QString pressImg)
{
    this->normalImgPath = normalImg;
    this->pressImgPath = pressImg;

    loadPicture(normalImg);
}

void MyPushButton::zoom1()
{
    zoom(QRect(this->x(), this->y(), this->width(), this->height()),
         QRect(this->x(), this->y() + 10, this->width(), this->height()),
         200);
}

void MyPushButton::zoom2()
{
    zoom(QRect(this->x(), this->y() + 10, this->width(), this->height()),
         QRect(this->x(), this->y(), this->width(), this->height()),
         200);
}

void MyPushButton::mousePressEvent(QMouseEvent *e)
{
    if (!this->pressImgPath.isEmpty()) {
        loadPicture(this->pressImgPath);
    }
    // 让父类执行其他内容
    return QPushButton::mousePressEvent(e);
}

void MyPushButton::mouseReleaseEvent(QMouseEvent *e)
{
    if (!this->pressImgPath.isEmpty()) {
        loadPicture(this->normalImgPath);
    }
    // 让父类执行其他内容
    return QPushButton::mouseReleaseEvent(e);
}

void MyPushButton::zoom(const QVariant &start, const QVariant &end, int msecs)
{
    // 创建动态对象
    auto animation = new QPropertyAnimation(this, "geometry");
    // 设置动画时间间隔
    animation->setDuration(msecs);
    // 起始位置
    animation->setStartValue(start);
    // 结束为止
    animation->setEndValue(end);
    // 设置弹跳曲线
    animation->setEasingCurve(QEasingCurve::OutBounce);
    // 执行动画
    animation->start();
}

bool MyPushButton::loadPicture(const QString &pic)
{
    QPixmap pix;
    bool ret = pix.load(pic);
    if (!ret) {
        qDebug() << pic << "图片加载失败";
        return false;
    }

    // 设置图片固定大小
    this->setFixedSize(pix.width(), pix.height());
    // 设置不规则图片样式
    this->setStyleSheet("QPushButton{border:0px;}");
    // 设置图标
    this->setIcon(pix);
    // 设置图标大小
    this->setIconSize(QSize(pix.width(), pix.height()));
    return true;
}
